package com.gu.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import com.aliyun.oss.OSSException;
import com.gu.config.OssProperties;
import com.gu.service.OssService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * Description:  aliyun oss 文件上传
 *
 * @Autor: Rolin
 * datetime: 05-19-14:34
 */

@Service
public class OssServiceImpl implements OssService {

    @Autowired
    private OssProperties ossProperties;

    @Override
    public String uploadFile(MultipartFile file) {
        //获取配置文件信息：
        String endpoint = ossProperties.getEndpoint();
        String keyId = ossProperties.getKeyId();
        String keySecret = ossProperties.getKeySecret();
        String bucketName = ossProperties.getBucketName();

        // 创建OSSClient实例。
        OSS ossClient = new OSSClientBuilder().build(endpoint, keyId, keySecret);
        String filePath = "";
        try {
            //获取文件的名称和输入流
            InputStream inputStream = file.getInputStream();
            String filename = file.getOriginalFilename();

            //日期文件夹+uuid
            filename  = new SimpleDateFormat("yyyy/MM/dd/").format(new Date())+UUID.randomUUID().toString().replaceAll("-", "") + filename;

            //上传文件到 oss
            ossClient.putObject(bucketName, filename, inputStream);
            //  https://edu-yuyikao8002.oss-cn-hangzhou.aliyuncs.com/pig.jpg
            filePath = "https://"+bucketName+"."+endpoint+"/"+filename;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return filePath;
    }


    @Override
    public boolean deleteByUrl(String coverName) {

        //获取配置文件信息：
        String endpoint = ossProperties.getEndpoint();
        String accessKeyId = ossProperties.getKeyId();
        String accessKeySecret = ossProperties.getKeySecret();
        String bucketName = ossProperties.getBucketName();

        OSS ossClient = new OSSClientBuilder().build(endpoint, accessKeyId, accessKeySecret);

        try {
            // 删除文件或目录。如果要删除目录，目录必须为空。
            ossClient.deleteObject(bucketName, coverName);
        } catch (OSSException oe) {
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
        }  finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }

        return true;
    }
}
